package com.pipestream;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

/**
 * @PackageName:com.pipestream
 * @ClassName:Test
 * @Description: 使用PipedlnputStream和PipedOutputStream管道字节流在线程之间传递数据
 * @Author: zhangxiaoyu
 * @date 2021/1/18 15:28
 */
public class Test {

    public static void main(String[] args){
         //定义管道字节流
         PipedInputStream inputStream = new PipedInputStream();
         PipedOutputStream outputStream = new PipedOutputStream();

         //在输入管道流与输出管道流直接建立连接
        try {
            inputStream.connect(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //创建线程向管道流中写入数据
        new Thread(new Runnable() {
            @Override
            public void run() {
                writeData(outputStream);
            }
        }).start();

        //定义线程从管道流读取数据
         new Thread(new Runnable() {
             @Override
             public void run() {
                 readData(inputStream);
             }
         }).start();
    }

    //定义方法 向管道流中写入数据
     public static  void  writeData(PipedOutputStream pipedOutputStream){
        //分别把0-100之间的数写入到管道中
         try {
             for (int i =0;i<100;i++){
                 String data = ""+i;
                 pipedOutputStream.write(data.getBytes()); //把一个字节数组写入到输出管道流中
             }
             pipedOutputStream.close();
         } catch (IOException e) {
             e.printStackTrace();
         }

     }

    //定义方法从管道流中读取数据
    public static void  readData(PipedInputStream pipedInputStream){
        byte[] bytes = new byte[1024];
        //从管道输入字节流中读取字节保存到字节数组中
        try {
            int len =  pipedInputStream.read(bytes);  //返回读到的字节数，如果没有返回-1
            while (len!=-1){
                //把数组中从0开始讲到的len个字节转换为字符串打印
                System.out.println(new String(bytes,0,len));
                //继续从管道中读取数据
                len = pipedInputStream.read(bytes);
            }
            pipedInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
